<template>
  <div class="shell">
    <!-- <h1>政府收售</h1>
     -->
    <div class="action-bar">
      <div class="tab-group">
        <button 
          class="tab-btn"
          :class="{ active: activeTab === 'sell' }"
          @click="handleTabChange('sell')"
        >
          出售
        </button>
        <button 
          class="tab-btn"
          :class="{ active: activeTab === 'buy' }"
          @click="handleTabChange('buy')"
        >
          收购
        </button>
      </div>

      <div class="search-group">

        <PublishButton 
          v-if="activeTab === 'buy' && store.userdata.role_name === 'gov'"
          :type="activeTab"
          @publish="handlePublishSuccess"
        />
        <PublishGoodsButton 
          v-if="activeTab === 'sell' && store.userdata.role_name === 'gov'"
          :type="activeTab"
          @fresh="handleRefresh"
          @publish="handlePublishSuccess"
        />
        <el-button
          type="primary"
          :icon="Refresh"
          @click="handleRefresh"
          :loading="loading"
        >
          刷新
        </el-button>
        <div class="search-box">
          <el-input
            v-model="searchText"
            :placeholder="activeTab === 'buy' ? '搜索公告标题' : '搜索农产品'"
            class="search-input"
            clearable
            @clear="resetSearch"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button 
            type="success" 
            @click="handleSearch" 
            :loading="searching"
          >
            搜索
          </el-button>
        </div>
      </div>
    </div>

    <div class="content-grid" v-loading="loading" element-loading-text="加载中...">
      <!-- 收购列表 -->
      <template v-if="activeTab === 'buy'">
        <PurchaseItem 
          v-for="item in displayList" 
          :key="item.article_id" 
          :data="item"
          :type="activeTab"
          @view-detail="handleViewDetail"
        />
      </template>
      
      <!-- 出售列表 -->
      <template v-else>
        <SellGoodsItem
          v-for="item in displayList"
          :key="item.product_id"
          :goods="item"
          :showDetail="true"
          :showOffShelf="false"
          :showStatus="false"
        />
      </template>
    </div>

    <el-empty 
      v-if="!loading && displayList.length === 0"
      description="暂无数据"
    />

    <div class="pagination" v-show="total > 0">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMainStore } from '@/stores'
import PurchaseItem from '../components/PurchaseItem.vue'
import SellGoodsItem from '../components/SellGoodsItem.vue'
import PublishButton from '../components/PublishButton.vue'
import PublishGoodsButton from '../components/PublishGoodsButton.vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { inject } from 'vue'

const router = useRouter()
const store = useMainStore()
const $axios = inject('$axios')
const $tools = inject('$tools')

const activeTab = ref('buy')
const searchText = ref('')
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)
const loading = ref(false)
const searching = ref(false)
// 列表数据
const buyList = ref([])
const sellList = ref([])

// 计算显示列表
const displayList = computed(() => {
  const list = activeTab.value === 'buy' ? buyList.value : sellList.value
  total.value = list.length
  
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  
  return list.slice(start, end)
})

// 获取数据列表
const fetchArticles = async () => {
  loading.value = true
  try {
    if (activeTab.value === 'buy') {
      // 获取收购列表
      const response = await $axios.get('/article/gov')
      if (response.data.code === 200) {
        const data = response.data.data
        buyList.value = data.filter(item => item.title.includes('收购'))
        store.setBuyList(buyList.value)
      } else {
        $tools.alertMsg(response.data.msg || '获取数据失败','error')
      }
    } else {
      // 获取出售列表
      const response = await $axios.get('/agri_products/gov')
      if (response.data.code === 200) {
        const data = response.data.data.map(item => ({
          ...item,
          created_at: new Date(item.created_at).toLocaleString()
        }))
        sellList.value = data
        store.setSellList(sellList.value)
      } else {
        $tools.alertMsg(response.data.msg || '获取数据失败','error')
      }
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    $tools.alertMsg('获取数据失败，请稍后重试','error')
  } finally {
    loading.value = false
  }
}

// 刷新方法
const handleRefresh = () => {
  searchText.value = ''
  currentPage.value = 1
  store.setCurrentPage(1)
  fetchArticles()
}

// 搜索处理
const handleSearch = async () => {
  if (!searchText.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  searching.value = true
  currentPage.value = 1
  store.setCurrentPage(1)
  try {
    if (activeTab.value === 'buy') {
      // 收购搜索
      const response = await $axios.get('/article/search', {
        params: {
          title: searchText.value.trim(),
          role: 'gov'
        }
      })

      if (response.data.code === 200) {
        const searchResults = response.data.data
        buyList.value = searchResults.filter(item => item.title.includes('收购'))
        store.setBuyList(buyList.value)
      } else {
        $tools.alertMsg(response.data.msg || '搜索失败','error')
      }
    } else {
      // 出售搜索
      const response = await $axios.get('/agri_products/search', {
        params: {
          title: searchText.value.trim(),
          role: 'gov'
        }
      })

      if (response.data.code === 200) {
        sellList.value = response.data.data.map(item => ({
          ...item,
          created_at: new Date(item.created_at).toLocaleString()
        }))
        store.setSellList(sellList.value)
      } else {
        $tools.alertMsg(response.data.msg || '搜索失败','error')
      }
    }
  } catch (error) {
    console.error('搜索失败:', error)
    $tools.alertMsg('搜索失败，请稍后重试','error')
  } finally {
    searching.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchText.value = ''
  fetchArticles()
}

// 页面加载时获取数据
onMounted(() => {
  currentPage.value = store.currentPage
  activeTab.value = store.activeGov
  console.log('activeTab:', activeTab.value)
  fetchArticles()
})

// 处理页面切换
const handlePageChange = (page) => {
  currentPage.value = page
  store.setCurrentPage(page)
  // window.scrollTo({
  //   top: 0,
  //   behavior: 'smooth'
  // })
}

// 处理查看详情
const handleViewDetail = (id) => {
  if (activeTab.value === 'buy') {
    const currentArticle = buyList.value.find(item => item.article_id === id)
    store.setCurrentArticle(currentArticle)
    router.push(`/home/artiDetail/${id}`)
  } else {
    router.push(`/home/detail/${id}`)
  }
}

// 处理标签切换
const handleTabChange = (tab) => {
  activeTab.value = tab
  store.setActiveGov(tab)
  currentPage.value = 1
  store.setCurrentPage(1)
  if (searchText.value) {
    resetSearch()
  } else {
    loading.value = true
    fetchArticles()
  }
}

// 处理发布成功
const handlePublishSuccess = () => {

  currentPage.value = 1;
  store.setCurrentPage(1);
  
  // 重新获取数据进行刷新
  fetchArticles();
}
</script>

<style lang="less" scoped>
.shell {
  padding: 20px;

  h1 {
    font-size: 24px;
    color: #319A19;
    margin-bottom: 20px;
  }

  .action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);

    .tab-group {
      display: flex;
      gap: 10px;

      .tab-btn {
        min-width: 80px;
        height: 32px;
        line-height: 30px;
        padding: 0 15px;
        border: 1px solid #dcdfe6;
        background: #fff;
        color: #606266;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          border-color: #319A19;
          color: #319A19;
        }

        &.active {
          background: #319A19;
          border-color: #319A19;
          color: #fff;
        }
      }
    }

    .search-group {
      display: flex;
      align-items: center;
      gap: 16px;

      .search-box {
        display: flex;
        gap: 8px;

        .search-input {
          width: 300px;

          :deep(.el-input__wrapper) {
            box-shadow: 0 0 0 1px #319A19 inset;
            
            &.is-focus {
              box-shadow: 0 0 0 1px #319A19 inset;
            }
          }
        }
      }
    }
  }

  .content-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    margin-bottom: 20px;
    min-height: 200px;
  }

  .pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    padding: 20px 0;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  }
}

@media screen and (max-width: 1200px) {
  .shell {
    .content-grid {
      grid-template-columns: 1fr;
    }
  }
}

@media screen and (max-width: 768px) {
  .shell {
    padding: 12px;

    .action-bar {
      flex-direction: column;
      gap: 16px;

      .search-group {
        width: 100%;
        flex-direction: column;

        .search-box {
          width: 100%;

          .search-input {
            width: 100%;
          }
        }
      }
    }
  }
}
</style>